package edu.uoc.tfc.web.tags;



import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;

import org.apache.commons.lang.StringUtils;



public class HiddenFieldTag extends AbstractFormFieldTag 
{



    private static final long serialVersionUID = 1L;

	private boolean show = false;



	public boolean isShow() {
	    return show;
    }



	public void setShow(boolean show) {
	    this.show = show;
    }



	@Override
	public int doStartTag() throws JspException
	{
		try
		{
			initialize();
			JspWriter out = pageContext.getOut();
			doStartFormField(out);
		}
		catch (Exception ex)
		{
			String message = "Error generando Campo oculto de formulario: " + this.getProperty();
			throw new JspException(message);
		}
		
		return SKIP_BODY;
	}



	@Override
    public int doEndTag() throws JspException
    {
	    return EVAL_PAGE;
    }



	@Override
    protected void doStartFormField(JspWriter out) throws JspException
	{
		try
		{
			if (isShow())
			{
				write(out,"<input type=\"text\" name=\"" + getName() + "\" id=\"" + getId() + "\" value=\"" + getValue() + "\" />");
			}
			else
			{
				write(out,"<input type=\"hidden\" name=\"" + getName() + "\" id=\"" + getId() + "\" value=\"" + getValue() + "\" />");
			}

			if (StringUtils.isNotBlank(getLinkedField()))
			{
				write(out, "<script type=\"text/javascript\">");
				write(out, "  $(document).ready(function() {");
				write(out, "    var linkedField = $(\"#" + getLinkedField() + "\");");
				write(out, "    if (linkedField){");
				write(out, "      linkedField.val(\"" + getValue() + "\");");
				write(out, "        $(\"#" + getId() + "\").change(function(){");
				write(out, "          $(\"#" + getLinkedField() + "\").val($(this).val());");
				write(out, "        });");
				write(out, "    }");
				write(out, "  });");
				write(out, "</script>");
			}
		}
		catch (Exception ex)
		{
			String message = "Error generando Campo oculto de texto: " + this.getProperty();
			throw new JspException(message);
		}
	}



	@Override
    protected void doEndFormField(JspWriter out) throws JspException
    {
		// No hacemos nada
    }



}
